import Taro from '@tarojs/taro';
import {Image, View, Text, Block} from '@tarojs/components';
import {appConfig, request, unite} from '../../../utils/index';
import close from '../../../asset/images/close.png';
import Select from '../../../asset/myImages/coupon_bg.png';
import SelectIn from '../../../asset/images/select_in.png';
import './affirmDetail.scss';

class AffirmDetail extends Taro.Component {
    config = {
        navigationBarTitleText: '确定订单',
        backgroundColor: '#fff',
    };

    state = {
        detailData: [],
        couponData: [], //可用优惠券列表
        couponIx: null, //选择优惠券
        numIx: 1, //人数
        couponType:false,
        price: null, //单价价格
        money: null, //总价
        agreements: true, //协议
    };

    componentDidMount() {
        this.getDetail();
        this.getCoupon(); //获取优惠券
    }

    //获取课程详情
    getDetail = () => {
        const option = this.$router.params;
        console.log(option);
        const params = {
            url: '/wx/firstPage/getClassDetail',
            data:{
                classId: option.classId,
                dispatchId: option.dispatchId,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data && res.data.classRoom) {
                        this.setState({
                            detailData: res.data,
                            price: res.data.price,
                            money: res.data.price,
                        })
                    }
                }
            }
        })
    };

    //获取优惠券
    getCoupon = () => {
        const params = {
            url: '/wx/coupon/listCurUserValidCoupons',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            couponData: res.data,
                        })
                    }
                }
            }
        })
    };

    //选择人数
    selectNumIx = (num) => {
        const {price, couponData, couponIx} = this.state;
        let money = 0;
        if (couponIx !== null) {
            money = (Number(price) * num) - couponData[couponIx].favourableCharge;
        } else {
            money = (Number(price) * num);
        }
        this.setState({
            numIx: num,
            money,
        })
    };

    //优惠卷选择
    couponStatus = () => {
        this.setState(PrevState => ({
            couponType: !PrevState.couponType
        }))
    };

    //提交支付
    submit = () => {
        const {numIx, price, couponIx, couponData, money, agreements} = this.state;
        const option = this.$router.params;
        let couponId = null;
        if (couponIx !== null) {
            couponId = couponData[couponIx].couponId
        }
        if (!agreements) return unite.showToast('请同意协议后购买');
        const params = {
            url: '/wx/pay/buyCourse',
            data:{
                classId: option.classId, //课程ID
                dispatchId: option.dispatchId, //课程安排ID
                studentNum: numIx, //上课的实际人数
                couponId: couponId ? [couponId] : null, //优惠券ID
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    unite.showToast(res.data.msg)
                    // this.onMiniPay(res);
                    Taro.navigateTo({
                        url: '../affirm-success/affirmSuccess?price=' + money
                    })
                }
            }
        })
    };

    //小程序支付
    onMiniPay = info => {
        const {money} = this.state;
        Taro.requestPayment({
            timeStamp: info.data.timeStamp.toString(),
            nonceStr: info.data.nonceStr,
            package: info.data.packageValue,
            signType: info.data.signType,
            paySign: info.data.paySign,
            success: () => {
                Taro.navigateTo({
                    url: '../affirm-success/affirmSuccess?price=' + money
                })
            },
            fail: () => {
                console.log('支付失败');
            },
        });
    };

    //选择优惠券
    selectIx = (index, minCharge) => {
        const {money, numIx} = this.state;
        if (Number(money) < Number(minCharge)) return unite.showToast('满' + minCharge + '元可用');
        this.setState(prveState => ({
            couponIx: prveState.couponIx == index ? null : index,
            money: prveState.couponIx == index ? (Number(prveState.price)*numIx) : (Number(prveState.price)*numIx) - Number(prveState.couponData[index].favourableCharge)
        }))
    };

    //协议同意 不同意
    agreementStatus = () => {
        this.setState(prveState => ({
            agreements : !prveState.agreements
        }));
    };

    couponSumbit = () => {
        this.couponStatus();
    };


    render() {
        const {numIx, couponType, detailData, money, couponData, couponIx, price, agreements} = this.state;
        return (
            <View className="page">
                {detailData && detailData.length != 0 &&(
                    <Block>
                        <View className="affirm-head">
                            <View className="affirm-head-wrap">
                                <Image className="affirm-head-img" src={detailData.avatar}/>
                                <View className="affirm-head-title">
                                    <View className="head-title-name">{detailData.className}</View>
                                    {/*<View className="head-title-time">时间：{detailData.classDate +  detailData.classWeekDay +  detailData.classBeginTime + '~' + detailData.classEndTime}</View>*/}
                                    <View className="head-title-address">{detailData.classRoom.address}</View>
                                </View>
                            </View>
                            {/*<View className="affirm-head-specs">*/}
                            {/*    <View className="head-specs-left">规模：{detailData.classScaleName}</View>*/}
                            {/*    <View className="head-specs-right">价格：￥{detailData.price}/节</View>*/}
                            {/*</View>*/}
                        </View>
                        <View className="affirm-head-select">
                            <View className="head-select-item select-item-br">
                                <View>上课时间</View>
                                <View className="head-title-time">
                                    {detailData.classDate  +' '+   detailData.classWeekDay +' '+  detailData.classBeginTime + '~' + detailData.classEndTime}
                                </View>
                            </View>
                            <View className="head-select-item select-item-br">
                                <View>规模</View>
                                <View className="select-item-text">{detailData.classScaleName}</View>
                            </View>
                        </View>
                        <View className="affirm-head-select">
                            <View className="head-select-item">
                                <View>人数</View>
                                <View className="head-select-right flex-lr">
                                    <View className={`select-right-item ${numIx == 1 ? 'select-right-item-active' : ''}`} onClick={this.selectNumIx.bind(this, 1)}>1人</View>
                                    <View className={`select-right-item ${numIx == 2 ? 'select-right-item-active' : ''}`} onClick={this.selectNumIx.bind(this, 2)}>2人</View>
                                    <View className={`select-right-item ${numIx == 3 ? 'select-right-item-active' : ''}`} onClick={this.selectNumIx.bind(this, 3)}>3人</View>
                                </View>
                            </View>
                            <View className="head-select-item select-item-br" onClick={this.couponStatus}> {/*onClick={this.couponStatus}*/}
                                <View>优惠券</View>
                                <View className="select-item-text">{couponIx === null ? '请选择' : '-' + couponData[couponIx].favourableCharge} <Text className="arrow"></Text> </View>
                            </View>
                        </View>
                        <View className="affirm-head-select">
                            <View className="head-select-item">
                                <View>单价</View>
                                <View className="select-item-text">{'¥' + price}</View>
                            </View>
                            <View className="head-select-item select-item-br">
                                <View className="select-item-name">实付</View>
                                <View className="head-select-money select-item-text">¥{money}</View>
                            </View>
                        </View>
                        <View className="affirm-bt-wrap">
                            <View className="agreement-texts flex-center" onClick={this.agreementStatus}>
                                <View className={`quan ${agreements ? 'quan-in' : ''}`}></View>
                                <View className="text">《用户协议》</View>
                                <View>&</View>
                                <View className="text">《订单规则》</View>
                            </View>
                            <View className="affirm-bt" onClick={this.submit}>提交订单</View>
                        </View>
                    </Block>
                )}
                {couponType &&(
                    <View className="model-type" onClick={this.couponStatus}>
                        <View className="model-type-wrap" onClick={(e) => {e.stopPropagation()}}>
                            <View className="names">课时</View>
                            <View className="flex-l select-lt">
                                <View className="select-item select-item-active flex-center">1课时</View>
                                {/*<View className="select-item select-item-active flex-center">3课时</View>*/}
                            </View>
                            <View className="names">优惠券</View>
                            <View className="model-type-list">
                                {couponData && couponData.map((item, index) => (
                                    <View className="model-type-item" key={index} onClick={this.selectIx.bind(this, index, item.minCharge)}>
                                        <Image className="model-img-bg" src={index === couponIx ? SelectIn : Select}/>
                                        <View className="model-wrap flex-l">
                                            <View className="model-left">
                                                <View className="left-money">¥{item.favourableCharge}</View>
                                                <View>满{item.minCharge}可用</View>
                                            </View>
                                            <View className="model-center">
                                                <View className="center-text">{item.clientName}</View>
                                                <View className="text-overflow">有效期：{item.effectTime}~{item.expireTime}</View>
                                            </View>
                                        </View>
                                    </View>
                                ))}
                            </View>
                            <View className="affirm-bt" onClick={this.couponSumbit}>确定</View>
                        </View>
                    </View>
                )}
            </View>
        )
    }
}

export default AffirmDetail;



